﻿using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using ScrumPilot.Domain.Models;
using ScrumPilot.TFSHelpers;
using Project = ScrumPilot.Domain.Models.Project;

namespace ScrumPilot.Domain.BPL
{
    public class ProjectAndKanbanServices : BusinessProcessLayer
    {
        public ProjectAndKanbanServices(TFSServices tfs) : base(tfs) { }

        protected Project GetProject(project pj)
        {
            var prj = this.GetProject(pj.projectid);

            if (prj != null)
            {
                prj.CurrentSprint = pj.currentsprint;
                prj.Selected = !pj.notuse;
                prj.SubscribeCheckin = pj.subscribecheckin.HasValue;
                prj.SubscribeWIChanged = pj.subscribewichanged.HasValue;
                return prj;
            }
            return null;
        }

        protected Project GetProject(int projectid, Boolean allIteration = true)
        {
            var tpj = TFS.GetProject(projectid);

            if (tpj != null)
            {
                return (new Project
                {
                    ID = projectid,
                    Name = tpj.Name,
                    Iterations = RecurseNodeSprint(tpj.IterationRootNodes, allIteration)
                });
            }
            return null;
        }

        protected IEnumerable<Iteration> RecurseNodeSprint(NodeCollection nodes, Boolean allIteration = true)
        {
            var lstRet = new List<Iteration>();
            if (allIteration)
            {
                foreach (Node nd in nodes)
                {
                    if (nd.IsIterationNode)
                        lstRet.Add(new Iteration { ID = nd.Path, Name = nd.Name + " [" + nd.Path + "]",SID = nd.Id});

                    if (nd.HasChildNodes) // Recurse in subNodes
                        lstRet.AddRange(RecurseNodeSprint(nd.ChildNodes));
                }
            }
            else
            {
                foreach (Node nd in nodes)
                {
                    if (nd.HasChildNodes) // Recurse in subNodes
                        lstRet.AddRange(RecurseNodeSprint(nd.ChildNodes, false));
                    else if (nd.IsIterationNode)
                        lstRet.Add(new Iteration { ID = nd.Path, Name = nd.Name + " [" + nd.Path + "]", SID = nd.Id });

                }
            }
            return lstRet;
        }

    }
}
